/*
 * Copyright 2009 Millibit Systems.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package jp.millibit.fiber
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.clearTimeout;
	import flash.utils.setTimeout;
	
	import jp.millibit.core.assert;
	import jp.millibit.core.notnull;

	public class Fiber
	{
		private static var _idCounter:int = 0;

		private var _id:int;

		private var _errorHandler:Function;

		private var _schedules:Array;

		private var _timer:uint;

		private var _parent:Fiber;

		private var _complete:Boolean;

		private var _dispatcher:EventDispatcher;

		private var _forkedFibers:Object;

		private var _numForkedFibers:uint;

		public function Fiber()
		{
			_id = _idCounter++;
			_timer = 0;
			_schedules = [];
			_dispatcher = new EventDispatcher();
			_forkedFibers = {};
			_numForkedFibers = 0;
		}

		private function schedule(fn:Function):void
		{
			_schedules.push(fn);
			startTimer(false);
		}

		private function startTimer(force:Boolean):void
		{
			if (force === false && _timer !== 0)
			{
				return;
			}

			_timer = setTimeout(timerHandler, 0);
		}

		private function timerHandler():void
		{
			clearTimeout(_timer);

			var schedule:Function = _schedules.shift();
			if (schedule !== null)
			{
				schedule.call(null, function():void{
						startTimer(true);
					});
				return;
			}

			_timer = 0;
		}

		public function set errorHandler(value:Function):void
		{
			_errorHandler = value;
		}

		public function get errorHandler():Function
		{
			return _errorHandler;
		}

		public function get parent():Fiber
		{
			return _parent;
		}

		public function sleep(ms:uint):void
		{
			schedule(function(callback:Function):void{
					var timer:uint = setTimeout(function():void{
							clearTimeout(timer);
							callback();
						}, ms);
				});
		}

		public function complete():void
		{
			if (_complete)
			{
				return;
			}
			_complete = true;
			_dispatcher.dispatchEvent(new Event("complete"));
		}

		public function join():void
		{
			schedule(function(callback:Function):void{
					if (_numForkedFibers === 0)
					{
						callback();
						return;
					}

					var fibers:Array = [];
					for (var id:String in _forkedFibers)
					{
						var fiber:Fiber = _forkedFibers[id];
						if (fiber._complete)
						{
							continue;
						}

						fibers.push(fiber);
					}

					if (fibers.length === 0)
					{
						callback();
						return;
					}

					var count:uint = fibers.length;
					for (var i:int = 0, len:uint = fibers.length; i < len; i++)
					{
						(function(fiber:Fiber):void{
								fiber._dispatcher.addEventListener("complete", function(e:Event):void{
										fiber._dispatcher.removeEventListener("complete", arguments.callee);

										if (--count === 0){
											callback();
										}
									});
							})(fibers[i]);
					}
				});
		}

		public function fork():Fiber
		{
			var fiber:Fiber = new Fiber();
			fiber._parent = this;
			_numForkedFibers++;
			_forkedFibers[fiber._id] = fiber;

			fiber._dispatcher.addEventListener("complete", function(e:Event):void{
					fiber._dispatcher.removeEventListener("complete", arguments.callee);
					_numForkedFibers--;
					delete _forkedFibers[fiber._id];
				});

			return fiber;
		}

		public function execute(task:ITask, args:Array = null):CallbackQueue
		{
			notnull(task, "task");

			if (task is Task)
			{
				return call0(task as Task, args);
			}
			return call0(new Task(task), args);
		}

		public function call(closure:Function, args:Array = null):CallbackQueue
		{
			notnull(closure, "closure");

			return call0(Task.create(closure), args);
		}

		private function call0(task:Task, args:Array):CallbackQueue
		{
			var queue:CallbackQueue = new CallbackQueue();
			var thiz:Fiber = this;
			schedule(function(callback:Function):void{
					var exec:Execution = Execution.create(thiz, args);
					task.start(queue, exec, callback);
				});

			return queue;
		}
	}
}
